using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using CSP.Model.Presenter;
using CSP.Model.Entities;
using System.Collections.Generic;
using System.Web.Configuration;
using System.Globalization;
using Facebook.Utility;
using Facebook.Schema;
using System.ComponentModel;
using Microsoft.SharePoint;

namespace eGov.SharePoint.MyPeeps.WebControls
{
    public partial class WhatsOnYourMind : System.Web.UI.UserControl, IWhatsOnYourMindPresenter, INotifyPropertyChanged
    {
        private WhatsOnYourMindPresenter presenter = null;
        protected global::System.Web.UI.WebControls.Label lblTitle;
        protected global::System.Web.UI.WebControls.TextBox txtPeep;
        protected global::System.Web.UI.WebControls.ImageButton btnShare;
        protected global::System.Web.UI.WebControls.Button btnDelete;
        protected global::System.Web.UI.WebControls.Repeater rptPeeps;
        protected global::System.Web.UI.WebControls.Literal ltPeepValidator;
        protected global::System.Web.UI.HtmlControls.HtmlInputHidden hidtwitter;
        protected global::System.Web.UI.HtmlControls.HtmlInputHidden hidfacebook;
        protected global::System.Web.UI.WebControls.Image imgUser;
        protected HtmlGenericControl divExternalUpdates;
        protected HtmlGenericControl divFBConnect;
        protected HtmlGenericControl divFBPost;

        protected static string PROPERTY_EXTERNALUPDATES = WebConfigurationManager.AppSettings["WhatsOnYourMindExternalUpdates"];
        protected static string PROPERTY_FBAPIKEY = WebConfigurationManager.AppSettings["FacebookAPIkey"];
        protected static string PROPERTY_FBSECRET = WebConfigurationManager.AppSettings["FacebookSECRET"];

        public event PropertyChangedEventHandler PropertyChanged;

        private string _fbSessionKey;
        private long _fbUserID;


        public event System.EventHandler OnShareButonClicked ;

        #region Public Properties
        public string Title
        {
            get { return txtPeep.Text; }
            set { txtPeep.Text = value; }
        }
        public string User
        {
            get;
            set;
        }
        public string Password
        {
            get;
            set;
        }
        public DateTime Date
        {
            get { return DateTime.Now; }
        }
        public string SiteURL
        {
            get;
            set;
        }
        public string ListName
        {
            get;
            set;
        }
        public bool PostToTwitter
        {
            get
            {
                if (hidtwitter.Value.ToString() == string.Empty || hidtwitter.Value.ToString() == "Inactive")
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
        public bool PostToFB
        {
            get
            {
                if (hidfacebook.Value.ToString() == string.Empty || hidfacebook.Value.ToString() == "Inactive")
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
        public string UserImage
        {
            get { return imgUser.ImageUrl; }
            set { imgUser.ImageUrl = value; }
        }
        public string FBSessionKey
        {
            get { return this._fbSessionKey; }
            set
            {
                this._fbSessionKey = value;
                if (PropertyChanged != null)
                    this.PropertyChanged(this, new PropertyChangedEventArgs("FBSessionKey"));
            }
        }
        public long FBUserID
        {
            get { return this._fbUserID; }
            set
            {
                this._fbUserID = value;
                if (PropertyChanged != null)
                    this.PropertyChanged(this, new PropertyChangedEventArgs("FBUserID"));
            }
        }
        protected bool HasFBSession { get; set; }
        public string FBAPIkey
        {
            get
            {
                return PROPERTY_FBAPIKEY;
            }
        }
        public string FBSecretkey
        {
            get
            {
                return PROPERTY_FBSECRET;
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                presenter = new WhatsOnYourMindPresenter(this);
                if (!Page.IsPostBack)
                {
                    presenter.Load();
                }

                /// Verify logged user
                if (this.VerifySiteOwner() == false)
                {
                    this.btnShare.OnClientClick = "alert('You cannot post as this is not your personal page.')";
                    this.divExternalUpdates.Visible = false;
                }
                else
                {
                    this.btnShare.Click += new ImageClickEventHandler(btnShare_OnClick);

                    /// Apply web.config setting to hide/show external updates buttons
                    if (String.Compare(PROPERTY_EXTERNALUPDATES, "true", true, CultureInfo.InvariantCulture) == 0)
                    {
                        this.divExternalUpdates.Visible = true;

                        /// Configure FB Connection
                        if (!String.IsNullOrEmpty(this.FBSessionKey) && VerifyActiveFBSession() == true)
                        {
                            this.HasFBSession = true;
                            this.divFBConnect.Visible = false;
                            this.divFBPost.Visible = true;
                        }
                        else
                        {
                            this.HasFBSession = false;
                            this.divFBConnect.Visible = true;
                            this.divFBPost.Visible = false;
                        }
                    }
                    else this.divExternalUpdates.Visible = false;
                }
            }
            catch (Exception ex)
            {
                DisplayError(ex);
            }

        }
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (String.Compare(PROPERTY_EXTERNALUPDATES, "true", true, CultureInfo.InvariantCulture) == 0)
            {
                string scriptInitFBkey = "facebookInitScript";
                string scriptKey = "facebookConnectscript";

                string FBInitscript = String.Format(@"<script src='http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US'
                    type='text/javascript'></script><script type='text/javascript'>FB.init('{0}');</script>", new object[] { PROPERTY_FBAPIKEY });
                if (!Page.ClientScript.IsStartupScriptRegistered(scriptInitFBkey))
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), scriptInitFBkey, FBInitscript);

                if (this.Request.QueryString["session"] != null)
                {
                    string session = this.Request.QueryString["session"];
                    session_info info = Utilities.DeserializeJSONObject<session_info>(session);

                    this.FBSessionKey = info.session_key;
                    this.FBUserID = info.uid;

                    this.Response.Write(@"<script language='javascript'> {window.close();}</script>");
                    return;
                }

                if (this.Request.Url.ToString().EndsWith("?closewindow"))
                {
                    this.Response.Write(@"<script language='javascript'> {window.close();}</script>");
                    return;
                }

                if (!Page.ClientScript.IsStartupScriptRegistered(scriptKey) && !this.HasFBSession)
                {
                    string url = string.Format(@"https://www.facebook.com/login.php?api_key=03f969f3adc1998de4c71d646f4fa54c&display=popup&popup=1&extern=2&v=1.0&next={0}&cancel_url={1}&fbconnect=1&return_session=1&req_perms=offline_access,publish_stream",
                                  new object[] { this.Request.Url, this.Request.Url.ToString() + "?closewindow" });
                    string scriptBlock =
                       @"<script language='javascript'>

                function verifyFBConnected(FBConnectWindow)
                {
                    if(FBConnectWindow.closed)
                     {
                        clearInterval(fbUpdateInterval);
                        var prm = Sys.WebForms.PageRequestManager.getInstance();
                        prm._doPostBack('updatePanel_FacebookConnect', '');
                     }
                }
                function OpenFacebookConnectPopup()
                {
                    var winsettings = 'resizable=1,scrollbars=0,menubar=0,status=0,location=0,height=450px,width=500px';

                    // http://support.microsoft.com/kb/978725 - IE8 with UAC may result in window.open to return null
                    FBConnectWindow = window.open('%url%', '_blank' , winsettings);
                    fbUpdateInterval = setInterval('verifyFBConnected(FBConnectWindow);', 1000);
                }


                 function ReloadUpdates()
                 {
                            var prm = Sys.WebForms.PageRequestManager.getInstance();
                            
                            alert('Called');
                         
                 }
                </script>";
                    scriptBlock = scriptBlock.Replace("%url%", url).Trim(new char[] { ' ' });

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), scriptKey, scriptBlock);
                }
            }
        }
        protected void btnShare_OnClick(object sender, EventArgs e)
        {
            try
            {
                presenter.PostPeep();
                presenter.Load();

                HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.ToString());
                // Raise the tabclicked event.
                //if(this.OnShareButonClicked != null) 
                //this.OnShareButonClicked(this, new EventArgs());


               //Page.ClientScript.RegisterStartupScript(this.GetType(), new Guid().ToString(), @"<script language='javascript'> ReloadUpdates(); </script>;");
                //WebPartManager partManager = (WebPartManager)this.Parent.Parent;

                //foreach (Control c in this.Parent.Parent.Controls)
                //{

                //    if (c.GetType().ToString().IndexOf("PublishedUpdatesUserControl") > -1)
                //    {
                //        PublishedUpdatesUserControl publishedUpdates = (PublishedUpdatesUserControl)c;
                //        publishedUpdates.bt
                //    }
                //}

                //PublishedUpdatesUserControl control = (PublishedUpdatesUserControl)partManager.FindControl("PublishedUpdatesUserControl");

                

            }
            catch (Exception ex)
            {
                DisplayError(ex);
            }
        }
        protected void btnDelete_OnClick(object sender, EventArgs e)
        {
            try
            {
                presenter.DeleteAllPeeps();
                presenter.Load();

            }
            catch (Exception ex)
            {
                DisplayError(ex);
            }
        }
        public void BindUpdates(List<Peep> peeps)
        {
            try
            {
                rptPeeps.DataSource = peeps;
                rptPeeps.DataBind();
            }
            catch
            {
                throw;
            }
        }

        private void DisplayError(Exception ex)
        {
            this.Controls.Add(new LiteralControl("<div style='color:Red;display:none;'>" + ex.ToString() + "</div>"));
        }
        private bool IsPeepValid()
        {
            if (Title != null & Title.Trim() != string.Empty)
            {
                ltPeepValidator.Visible = false;
                return true;
            }
            return false;
        }

        private bool VerifyActiveFBSession()
        {
            try
            {
                Facebook.Session.ConnectSession connectsession = new Facebook.Session.ConnectSession(PROPERTY_FBAPIKEY, PROPERTY_FBSECRET);
                connectsession.RequiredPermissions = new List<Enums.ExtendedPermissions>();
                connectsession.RequiredPermissions.Add(Enums.ExtendedPermissions.publish_stream);
                Facebook.Rest.Api api = new Facebook.Rest.Api(connectsession);
                api.Session.SessionKey = this.FBSessionKey;
                api.Session.UserId = this.FBUserID;

                string query = string.Format("select publish_stream from permissions where uid = {0}", this.FBUserID);
                permissions_response _response = api.Fql.Query<permissions_response>(query);

                if (_response != null && _response.permissions.publish_stream == true)
                    return true; // Active only when permissions for offline mode and publishing are preserved
            }
            catch
            { }
            return false;
        }
        public void LogoutActiveFBSession()
        {
            try
            {
                Facebook.Session.ConnectSession connectsession = new Facebook.Session.ConnectSession(PROPERTY_FBAPIKEY, PROPERTY_FBSECRET);
                Facebook.Rest.Api api = new Facebook.Rest.Api(connectsession);
                api.Session.SessionKey = this.FBSessionKey;
                api.Session.UserId = this.FBUserID;
                api.Session.Logout();
            }
            catch { }
        }

        private bool VerifySiteOwner()
        {
            try
            {
                /// Matches the default site owner
                /// Owner property throws exception in case current user as insufficient permissions
                if (SPContext.Current.Site.Owner.LoginName == SPContext.Current.Web.CurrentUser.LoginName)
                    return true;
            }
            catch { }

            return false;
        }

    }

}
